<template>
  <div id="dictChildList">
    <vxe-toolbar perfect>
      <template #buttons>
        <!-- <vxe-button
          type="text"
          status="info"
          icon="vxe-icon-refresh"
          content="返回"
          @click="goBack"
        ></vxe-button> -->
        <vxe-button
          type="text"
          class="button-blue"
          icon="vxe-icon-refresh"
          content="刷新"
          :loading="tLoading"
          @click="findDictAndDetailList"
        ></vxe-button>
        <vxe-button
          type="text"
          class="button-blue"
          icon="vxe-icon-square-plus"
          content="新建字典值"
          @click="addDetail()"
        ></vxe-button>
        <vxe-button
          type="text"
          class="button-blue"
          icon="vxe-icon-save"
          content="保存"
          :loading="saveLoading"
          @click="saveDetailList"
        ></vxe-button>
      </template>
    </vxe-toolbar>
    <div class="tableBox">
      <vxe-table
        ref="detailTable"
        class="mytable-scrollbar"
        border="inner"
        align="center"
        height="auto"
        :data="detailList"
        :loading="tLoading"
        :row-config="{ isCurrent: true, isHover: true }"
        :keyboard-config="{
          isArrow: true,
          isTab: true,
          isEdit: true
        }"
        :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }"
        resizable
        show-overflow
        keep-source
      >
        <vxe-column
          v-for="(item, index) in dictList"
          :key="index"
          :field="item.code"
          :title="item.name"
          width="130"
          :edit-render="{}"
        >
          <template #default="{ row, rowIndex, column }">
            <span v-if="item.code == 'isEdit'">{{ row[item.code] === '1' ? '否' : '是' }}</span>
            <span v-else>{{ row[item.code] }}</span>
          </template>

          <template #edit="{ row, rowIndex, column }">
            <!-- 是否删改 开关 -->
            <vxe-switch
              v-model="row[item.code]"
              v-if="item.code == 'isEdit'"
              open-label="是"
              close-label="否"
              open-value="0"
              close-value="1"
            ></vxe-switch>

            <!-- 选择字典  -->
            <vxe-select
              v-model="row[item.code]"
              placeholder="可清除"
              clearable
              v-else-if="item.classify == '3'"
              @focus="getSecletDictDetailById(item)"
            >
              <vxe-option
                v-for="(selectDetail, index) in selectDetailList"
                :key="index"
                :value="selectDetail.code"
                :label="selectDetail.name"
              ></vxe-option>
            </vxe-select>

            <!-- 选择动态表  -->
            <vxe-select
              v-model="row[item.code]"
              placeholder="可清除"
              clearable
              v-else-if="item.classify == '4'"
              @focus="getTableDataList(item)"
              @change="selectTableData($event, item, row)"
            >
              <vxe-option
                v-for="(tableData, index) in tableDataList"
                :key="index"
                :value="tableData[item.correColumn]"
                :label="tableData[item.correColumn2]"
              ></vxe-option>
            </vxe-select>

            <!-- 自动生成 -->
            <vxe-input
              v-else-if="
                dictList.find((it) => it.classify == '2') &&
                dictList.find((it) => it.classify == '2').correField == item.code
              "
              @change="getBdsResult(item.code, row[item.code], row)"
              v-model="row[item.code]"
              type="text"
            ></vxe-input>

            <!-- 禁用 -->
            <vxe-input
              v-else-if="item.classify == '1'"
              v-model="row[item.code]"
              disabled
              type="text"
            ></vxe-input>
            <!-- 组件类型什么也没选 -->
            <vxe-input v-else v-model="row[item.code]" type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="sx" title="排序" :edit-render="{}">
          <template #edit="{ row, rowIndex, column }">
            <vxe-input v-model="row.sx" type="text"></vxe-input>
          </template>
        </vxe-column>

        <vxe-column title="操作" align="center" fixed="right">
          <template #default="{ row }">
            <vxe-button
              type="text"
              status="danger"
              icon="vxe-icon-delete"
              circle
              v-if="panduanIsEdit(row)"
              @click.native="deleteDetail(row)"
            ></vxe-button>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
let { proxy }: any = getCurrentInstance();
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { funBdsJsResult } from '@/utils/Expression';
import {isEmpty} from "lodash"; //函数公式

//暴露属性和方法
defineExpose({
  initPage,
  clearDictAndDetailList
});

// 全局变量定义区 ==========
let tLoading = ref(false); //表格加载状态+刷新
let saveLoading = ref(false); //保存按钮加载
let detailTable = ref(); //表格标记ref
let detailList: any = reactive([]); //表格数据
let dictList: any = reactive([]); //表格列遍历的
let selectDetailList: any = reactive([]); //选择字典
let tableDataList: any = reactive([]); //选择动态表集合
let dictId = '';
let dictCode = '';
let backUrl = '';

// onMounted(() => {
//   console.log(proxy.$route.query);
//   dictId = proxy.$route.query.id;
//   backUrl = proxy.$route.query.url.toString();
//   findDictAndDetailList();
// });

// 方法定义区 =============
function initPage(row: any) {
  console.log('row',row)
  detailList.length = 0;
  dictId = isEmpty(row.id)?'' : row.id;
  dictCode = isEmpty(row.code)?'' : row.code;//适应通过 父code去查找字典值
  findDictAndDetailList(); //获取表格数据
}
// 清空数据
function clearDictAndDetailList() {
  dictList.length = 0; //放入数据前清空数据
  detailList.length = 0;
}
// 获取表格数据
function findDictAndDetailList() {
  tLoading.value = true;
  dictList.length = 0; //放入数据前清空数据
  detailList.length = 0;
  const url = '/api/sys/basDict/findDictAndDetailList';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { pid: dictId,pCode:dictCode } })
    .then((res: any) => {
      dictList.push(...res.data.dictList);
      detailList.push(...res.data.detailList);
      tLoading.value = false;
    })
    .catch((err: any) => {
      tLoading.value = false;
      // VxeMessage('获取表格数据失败',VxeNotifyType.error)
    });
}

// 新建字典值
function addDetail() {
  if (dictList.length > 0) {
    const row: any = {};
    for (const item of dictList) {
      row[item.code] = '';
    }
    row.isEdit = '0';
    row.sx = detailList.length == 0 ? 1 : Number(detailList[detailList.length - 1].sx) + 1;
    detailList.push(row);
  } else {
    VxeMessage('请选择基础字典', VxeNotifyType.warning);
  }
}

// 保存
async function saveDetailList() {
  // 获取表格实例
  let $Xtable = proxy.$refs.detailTable;
  if ($Xtable) {
    saveLoading.value = true;
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
      return p.commonId && p.commonId !== '';
    });
    // 拿到数组中没有id的数据为新增
    const InsertRecords = detailList.filter((e: any) => {
      return !e.commonId || e.commonId === '';
    });

    // 遍历发起请求  将筛选出有id的每一个对象（修改过的） 作为参数传递给后端
    const saveOrUpdateitems = [] as any[];

    updateRecords.forEach((e: any) => {
      let moduleAddParam = e;
      for (const item of dictList) {
        const itemtemp = JSON.parse(JSON.stringify(item));
        itemtemp.value = moduleAddParam[item.code];
        itemtemp.sx = moduleAddParam.sx;
        itemtemp.id = '';
        itemtemp.pid = item.id;
        itemtemp.grade = moduleAddParam.grade;
        itemtemp.commonId = moduleAddParam.commonId;
        saveOrUpdateitems.push(itemtemp);
      }
    });

    // 新增
    InsertRecords.forEach((e: any) => {
      const moduleAddParam = e;
      for (const item of dictList) {
        const itemtemp = JSON.parse(JSON.stringify(item));
        itemtemp.value = moduleAddParam[item.code];
        itemtemp.sx = moduleAddParam.sx;
        itemtemp.id = '';
        itemtemp.pid = item.id;
        itemtemp.grade = 2;
        saveOrUpdateitems.push(itemtemp);
      }
    });

    //批量一起新增
    const obj = {
      detailList: saveOrUpdateitems
    };

    proxy.$http
      .post('/api/sys/basDictDetail/saveOrUpdateDetail', obj)
      .then((res: any) => {
        if (res.status.code === 1) {
          if (res.status.code === 1) {
            VxeMessage(res.status.msg, VxeNotifyType.success);
            // setTimeout(() => {
            findDictAndDetailList();
            // }, 500);
          } else {
            VxeMessage(res.status.msg, VxeNotifyType.error);
          }
          saveLoading.value = false;
        }
      })
      .catch((err: any) => {
        VxeMessage('更新字典值异常', VxeNotifyType.error);
        saveLoading.value = false;
      });
  } else {
    return;
  }
}

async function saveDetailList1() {
  // 获取表格实例
  let $Xtable = proxy.$refs.detailTable;
  if ($Xtable) {
    saveLoading.value = true;
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
      return p.commonId && p.commonId !== '';
    });
    // 拿到数组中没有id的数据为新增
    const InsertRecords = detailList.filter((e: any) => {
      return !e.commonId || e.commonId === '';
    });

    // 遍历发起请求  将筛选出有id的每一个对象（修改过的） 作为参数传递给后端
    updateRecords.forEach((e: any) => {
      let moduleAddParam = e;
      const items = [] as any[];
      for (const item of dictList) {
        const itemtemp = JSON.parse(JSON.stringify(item));
        itemtemp.value = moduleAddParam[item.code];
        itemtemp.sx = moduleAddParam.sx;
        itemtemp.id = '';
        itemtemp.pid = item.id;
        itemtemp.grade = moduleAddParam.grade;
        itemtemp.commonId = moduleAddParam.commonId;
        items.push(itemtemp);
      }
      const obj = {
        detailList: items
      };
      proxy.$http
        .post('/api/sys/basDictDetail/editBatchDetail', obj)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('修改成功', VxeNotifyType.success);
            saveLoading.value = false;
          }
        })
        .catch((err: any) => {
          VxeMessage('修改失败', VxeNotifyType.error);
          saveLoading.value = false;
        });
    });

    // 新增
    InsertRecords.forEach((e: any) => {
      const moduleAddParam = e;
      const items = [] as any[];
      for (const item of dictList) {
        const itemtemp = JSON.parse(JSON.stringify(item));
        itemtemp.value = moduleAddParam[item.code];
        itemtemp.sx = moduleAddParam.sx;
        itemtemp.id = '';
        itemtemp.pid = item.id;
        itemtemp.grade = 2;
        items.push(itemtemp);
      }
      const obj = {
        detailList: items
      };
      proxy.$http
        .post('/api/sys/basDictDetail/addBatchDetail', obj)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('新增成功', VxeNotifyType.success);
            saveLoading.value = false;
          }
        })
        .catch((err: any) => {
          VxeMessage('新增失败', VxeNotifyType.error);
          saveLoading.value = false;
        });
    });
    setTimeout(() => {
      findDictAndDetailList();
      saveLoading.value = false;
    }, 500);
  } else {
    return;
  }
}

// 删除字典值
function deleteDetail(row: any) {
  proxy
    .$confirm('确定删除此字典？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const url = '/api/sys/basDictDetail/deleteBatchDetail';

      if (row.commonId) {
        proxy.$http.post(url, row).then((res: any) => {
          if (res.status.code === 400) {
            VxeMessage('删除字典值失败', VxeNotifyType.error);
          } else {
            VxeMessage('删除字典值成功', VxeNotifyType.success);
          }
          findDictAndDetailList();
        });
      } else {
        const $table = detailTable.value;
        if ($table) {
          await $table.remove(row);
          VxeMessage('删除字典值成功', VxeNotifyType.success);
        }
      }
    })
    .catch((err: any) => {
      // VxeMessage('删除异常',VxeNotifyType.error)
    });
}

function panduanIsEdit(row: any) {
  if (row.commonId == undefined) {
    return true;
  } else {
    if (row.isEdit == undefined) {
      return row.isParentEdit == '0';
    } else {
      if (!(row.isParentEdit == '0')) {
        return false;
      } else {
        return row.isEdit == '0';
      }
    }
  }
}

// 选择字典
function getSecletDictDetailById(row: any) {
  selectDetailList.length = 0; //放入数据前清空数据
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { pid: row.dict } })
    .then((res: any) => {
      selectDetailList.push(...res.data);
    })
    .catch((err: any) => {
      // VxeMessage('获取选择字典失败',VxeNotifyType.error)
    });
}

// 自动生成
function getBdsResult(code: any, value: any, row: any) {
  const dict = dictList.find((it: any) => it.classify == '2');
  const expression = dict.expression;
  row[dict.code] = funBdsJsResult(expression, value);
  //dictList.find((it) => it.classify == '2').correField == item.code
}

// 获取可用字典
function getTableDataList(row: any) {
  const columNameList = [];
  columNameList.push(row.correColumn);
  columNameList.push(row.correColumn2);
  console.log(row);

  tableDataList.length = 0; //放入数据前清空数据
  const url = '/api/sys/basDictTableField/getTableFieldAndDataList';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { tableName: row.correTable, columNameList: columNameList.join(',') } })
    .then((res: any) => {
      tableDataList.push(...res.data);
    })
    .catch((err: any) => {
      // VxeMessage('获取可用字典失败',VxeNotifyType.error)
    });
}

// 选择动态表
function selectTableData($event: any, item: any, row: any) {
  const tableData = tableDataList.find((tData: any) => tData[item.correColumn] == $event.value);
  row[item.correField] = tableData[item.correColumn2];
}

// 返回按钮  注释了的
function goBack(): void {
  if (backUrl) {
    proxy.$router.push(backUrl);
  } else {
    proxy.$router.go(-1); //返回上一层
  }
}
</script>

<style lang="scss" scoped>
#dictChildList {
  height: 100%;
  // 附加按钮间距
  .button-blue {
    margin: 5px 0 5px 5px;
  }
  .tableBox {
    height: calc(100% - 40px);
    background-color: $base-white;
  }
}
</style>
